#include "Game.h"
#include "Enemy.h"
#include "Player.h"
#include "InputHandler.h"
#include "MenuState.h"
#include "PlayState.h"

Game* Game::mInstance = NULL;

bool Game::Initialize(const char* title, int xpos, int ypos, int width, int height, bool fullscreen)
{
	if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
	{
		int flags = 0;
		if (fullscreen)
			flags = SDL_WINDOW_FULLSCREEN;

		//Init Window
		mWin = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
		if (mWin != NULL)
		{
			printf("Window created succesfully\n");
			mRenderer = SDL_CreateRenderer(mWin, -1, 0);

			if (mRenderer != NULL)
			{
				printf("Renderer created succesfully\n");
				SDL_SetRenderDrawColor(mRenderer, 255, 255, 255, 255);
			}
			else
			{
				printf("Error Creating Renderer: %s\n", SDL_GetError());
				return false;
			}

			if(TTF_Init() == -1)
			{
				printf("SDL_ttf could not initialize! SDL_ttf: %s\n", TTF_GetError());
				return false;
			}

			InputHandler::Instance()->Initialize();
			InputHandler::Instance()->InitializeJoysticks();
			mGameStateMachine = new GameStateMachine();
			mGameStateMachine->changeState(new MenuState());

			printf("Initialization Successful\n");
			mRunning = true;
			
			LoadStart();
			
			return true;
		}
		else
		{
			printf("Error Creating Window: %s\n", SDL_GetError());
			return false;
		}
	}
	else
	{
		mRunning = false;
		return false;
	}
}

void Game::Render()
{
	SDL_RenderClear(mRenderer);

	mGameStateMachine->Draw();

	SDL_RenderPresent(mRenderer);
}

void Game::Update()
{
	EventHandler();
	mGameStateMachine->Update();
}

void Game::EventHandler()
{
	InputHandler::Instance()->Update();
	if(InputHandler::Instance()->isKeyDown(SDL_SCANCODE_DELETE))
	{
		mGameStateMachine->changeState(new PlayState());
	}
}

void Game::Shutdown()
{
	printf("Shutting Down");
	InputHandler::Instance()->Shutdown();
	SDL_DestroyWindow(mWin);
	SDL_DestroyRenderer(mRenderer);
	SDL_Quit();
	Game::Instance()->mRunning = false;
}

void Game::LoadStart()
{
}
